package com.tang.thepath;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.tang.thepath.model.RequestModel;
import com.tang.thepath.service.BizService;
import com.tang.thepath.service.HttpManager;
import com.tang.thepath.service.HttpSubscriber;
import com.tang.thepath.util.BitmapUtil;

import java.util.List;

import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

public class RepairDetailActivity extends BaseActivity {

    private TextView tvCompanyName;
    private TextView tvAddress;
    private TextView tvContact;
    private TextView tvCarModel;
    private TextView tvIssue;
    private TextView tvReason;
    private TextView tvSaleTime;
    private LinearLayout imageContainer;
    private LinearLayout afterImageContainer;
    private ImageView imageAddPic;
    private static final int UPLOAD_REQUEST_CODE = 0x1001;
    private RequestModel.Repair repair;

    protected View.OnTouchListener imageTouchListener = new View.OnTouchListener (){

        @Override
        public boolean onTouch(View v, MotionEvent event) {
            if (event.getAction() == MotionEvent.ACTION_UP || event.getAction() == MotionEvent.ACTION_MOVE) {
                ((ImageView)v).clearColorFilter(); // 清除滤镜效果
            }
            if (event.getAction() == MotionEvent.ACTION_DOWN) {
                ((ImageView)v).setColorFilter(Color.parseColor("#77000000")); // 设置滤镜效果
            }
            return false;
        }
    };
    protected View.OnClickListener imageClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            ImageView iv = (ImageView) v;
            String url = iv.getTag().toString();
            Intent intent = new Intent(RepairDetailActivity.this,GalleryImagePreviewActivity.class);
            intent.putExtra("url",url);
            startActivity(intent);
        }
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_repair_detail);

        tvCompanyName = (TextView) findViewById(R.id.tv_company_name);
        tvAddress = (TextView) findViewById(R.id.tv_address);
        tvContact = (TextView) findViewById(R.id.tv_contact);
        tvCarModel = (TextView) findViewById(R.id.tv_car_model);
        tvIssue = (TextView) findViewById(R.id.tv_issue);
        tvReason = (TextView) findViewById(R.id.tv_reason);
        tvSaleTime = (TextView) findViewById(R.id.tv_sale_time);
        imageContainer = (LinearLayout) findViewById(R.id.pre_image_list_layout);
        afterImageContainer = (LinearLayout) findViewById(R.id.after_image_list_layout) ;
        imageAddPic = (ImageView) findViewById(R.id.img_add_after);


        Intent intent = getIntent();
        repair = (RequestModel.Repair)intent.getSerializableExtra("repair");

        tvCompanyName.setText(repair.companyName);
        tvAddress.setText(repair.address);
        tvContact.setText(repair.contact);
        tvIssue.setText(repair.issueTitle);
        tvReason.setText(repair.reason);
        tvSaleTime.setText(repair.saleTime.substring(0,10));
        tvCarModel.setText(repair.carModel);

        setTitle(repair.contact);
        loadImages(repair.images,imageContainer);
        if(repair.afterImages.size() > 0){
            imageAddPic.setVisibility(View.GONE);
            loadImages(repair.afterImages,afterImageContainer);
        }

        imageAddPic.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivityForResult(new Intent(RepairDetailActivity.this,UploadImageActivity.class),UPLOAD_REQUEST_CODE);
            }
        });
    }


    protected void loadImages(final List<String> images, final ViewGroup imageContainer){
        if(images.size() == 0){
            return;
        }
        //showLoading("正在加载图片");
        Observable.from(images)
                .subscribeOn(Schedulers.io())
                .map(new Func1<String, BitmapUrlHolder>() {

                    @Override
                    public BitmapUrlHolder call(String s) {
                        Bitmap bitmap = BitmapUtil.getBitmapByUrl(s);
                        return new BitmapUrlHolder(s,bitmap);
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<BitmapUrlHolder>() {
                    @Override
                    public void onCompleted() {
                        //dismisLoading();
                    }

                    @Override
                    public void onError(Throwable e) {
                        //dismisLoading();
                        toast(e.getMessage());
                    }

                    @Override
                    public void onNext(BitmapUrlHolder bitmapUrlHolder) {
                        //ImageView iv = (ImageView) inflater.inflate(R.layout.detail_image_view,null);
                        ImageView iv = new ImageView(getContext());
                        LinearLayout.LayoutParams layoutParams=new LinearLayout.LayoutParams(200, 200);
                        iv.setScaleType(ImageView.ScaleType.CENTER_CROP);
                        layoutParams.setMargins(0,0,10,0);
                        iv.setLayoutParams(layoutParams);
                        iv.setImageBitmap(bitmapUrlHolder.bitmap);
                        iv.setClickable(true);
                        iv.setOnTouchListener(imageTouchListener);
                        iv.setOnClickListener(imageClickListener);
                        iv.setTag(bitmapUrlHolder.url);
                        imageContainer.addView(iv);
                    }
                });
    }

    class BitmapUrlHolder {
        public String url;
        public Bitmap bitmap;

        public BitmapUrlHolder(String url,Bitmap bitmap){
            this.url = url;
            this.bitmap = bitmap;
        }
    }


    protected void updateImage(final List<String> images){
        if(images.size() == 0){
            return;
        }
        showLoading("正在更新图片");
        RequestModel.UpdateRepairRequest request = new RequestModel.UpdateRepairRequest();
        request.id = repair.id;
        request.afterImages = images;
        BizService.updateRepair(request).subscribe(new HttpSubscriber<RequestModel.IdResponse>() {
            @Override
            protected void onSuccess(RequestModel.IdResponse idResponse) {
                dismisLoading();
                for (int i=0;i<images.size();i++){
                    images.set(i, HttpManager.BASEURL+images.get(i));
                }
                loadImages(images,afterImageContainer);
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        if(requestCode == UPLOAD_REQUEST_CODE){
            if(resultCode == RESULT_OK){
                List<String> images = data.getStringArrayListExtra("images");
                if(images.size() > 0){
                    imageAddPic.setVisibility(View.GONE);
                    updateImage(images);
                }

            }
        }

    }
}
